package com.itheima.consultant;

import com.itheima.consultant.entity.ChatHistory;
import com.itheima.consultant.mapper.ChatHistoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;

import java.util.List;
import java.util.Map;

@RestController
public class ChatController {
    @Autowired
    private  ChatHistoryMapper chatHistoryMapper;
    private final ZhiPuAiChatModel chatModel;

    @Autowired
    public ChatController(ZhiPuAiChatModel chatModel) {
        this.chatModel = chatModel;
    }

    @GetMapping("/ai/generate")
    public Mono<Map<String, String>> generate(
            @RequestParam String message,
            @RequestParam(required = false, defaultValue = "anonymous") String userId
    ) {
        return Mono.fromCallable(() -> {
                    // 👇 这里是阻塞调用（如 chatModel.call）
                    String answer = chatModel.call(message);
                    return answer;
                })
                .subscribeOn(Schedulers.boundedElastic()) // 👈 切换到支持阻塞的线程池
                .flatMap(answer -> {
                    // 👇 保存数据库（如果也是阻塞操作，同样要异步化）
                    return Mono.fromRunnable(() -> chatHistoryMapper.save(userId, message, answer))
                            .then(Mono.just(Map.of("generation", answer)));
                })
                .onErrorResume(e -> {
                    // 错误处理
                    return Mono.just(Map.of("generation", "Error calling AI: " + e.getMessage()));
                });
    }
    @GetMapping("/ai/answer")
    public List<ChatHistory> answer(@RequestParam(required = false, defaultValue = "anonymous") String userId) {
        List<ChatHistory> chatHistory = chatHistoryMapper.findByUserId(userId);
            return chatHistory;
    }
//    @GetMapping(value = "/ai/generateStream", produces = "text/event-stream;charset=UTF-8")
//    public Flux<String> generateStream(@RequestParam String message) {
//        return chatModel.stream(message)
//                .map(content -> "data: " + content + "\n\n") // 👈 必须包装成 SSE 格式
//                .doOnSubscribe(s -> System.out.println("=== SSE Stream Started ==="))
//                .doOnComplete(() -> System.out.println("=== SSE Stream Finished ==="));
//    }
}